package com.czxy.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.czxy.tanhua.dubbo.config.IdWorker;
import com.czxy.tanhua.dubbo.mappers.UserInfoMapper;
import com.czxy.tanhua.entity.UserInfo;
import com.czxy.tanhua.mongo.Friend;
import com.czxy.tanhua.mongo.Movement;
import com.czxy.tanhua.mongo.MovementTimeline;
import com.czxy.tanhua.vo.MovementVo;
import com.czxy.tanhua.vo.PostUpdateVo;
import com.czxy.tanhua.vo.PublicPageVo;
import com.czxy.tanhua.vo.ResultList;
import com.mongodb.client.result.UpdateResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author 爱吃豆的土豆、
 * @Date 2023/4/8 13:49
 */
@DubboService
public class MovementApiImpl implements MovementApi{
    @Resource
    private IdWorker idWorker;
    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Override
    public ResultList findmovements(Long userid, PublicPageVo publicPageVo) {

        //创建封装信息类
        ResultList resultList = new ResultList();
        Query query = new Query();
        //查询用户详情信息
        UserInfo userInfo = userInfoMapper.selectById(userid);

        Criteria criteria = Criteria.where("userId").is(userid);
        long count = mongoTemplate.count(query, Movement.class);
        query.addCriteria(criteria).skip((publicPageVo.getPage()-1)* publicPageVo.getPagesize()).limit(publicPageVo.getPagesize().intValue());

        query.with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);

        ArrayList<MovementVo> movementVos = new ArrayList<>();


        for (Movement movement : movements) {
            //创建封装类
            MovementVo movementVo = new MovementVo(movement.getId().toString(),
                    userInfo.getId(),userInfo.getAvatar(),userInfo.getNickname(),userInfo.getGender(),userInfo.getAge(),
                    userInfo.getTags().split(","),movement.getTextContent(),movement.getMedias(),"",movement.getCreated().toString()
                    ,movement.getLikeCount(),movement.getCommentCount(),movement.getLoveCount(),0,0);

            movementVos.add(movementVo);
        }
        //设置列表
        resultList.setItems(movementVos);
        //设置当前页码
        resultList.setPage(publicPageVo.getPage().intValue());
        //设置总记录数
        resultList.setCounts((int) count);
        //设置页大小
        resultList.setPagesize(publicPageVo.getPagesize().intValue());
        //设置总页数
        resultList.setPages((int) (count%publicPageVo.getPagesize() == 0 ? count/ publicPageVo.getPagesize():(count/ publicPageVo.getPagesize())+1));

        return resultList;
    }

    @Override
    public void fabudongtai(PostUpdateVo postUpdateVo, Long userId, String mobile) {
        //保存动态到mongo动态表中
        Movement movement = new Movement();
        Long movement1 = idWorker.getNextId("movement");
        movement.setPid(movement1);
        movement.setUserId(userId);
        movement.setTextContent(postUpdateVo.getTextContent());
        movement.setMedias(postUpdateVo.getImages().toArray(new String[0]));
        movement.setState(0);
        movement.setLongitude(Double.valueOf(postUpdateVo.getLongitude()));
        movement.setLatitude(Double.valueOf(postUpdateVo.getLatitude()));
        movement.setLocationName(postUpdateVo.getLocation());
        movement.setCreated(new Date().getTime());
        //保存动态表
        Movement save = mongoTemplate.save(movement);

        //查询好友列表
        //构建条件
        Query query = new Query();
        Criteria criteria = Criteria.where("userId").is(userId);
        query.addCriteria(criteria);
        List<Friend> friends = mongoTemplate.find(query, Friend.class);

        //保存时间线数据
        for (Friend friend : friends) {
            MovementTimeline movementTimeline = new MovementTimeline(save.getCreated(),friend.getFriendId(),save.getId(),save.getUserId());
            mongoTemplate.save(movementTimeline);
        }
        //处理结束
    }


    @Override
    public ResultList friendmovements(PublicPageVo publicPageVo, Long userId) {
        //创建封装类
        ResultList movementVoResultList = new ResultList<>();
        //通过userId
        Query query = new Query();
        query.addCriteria(Criteria.where("friendId").is(userId));
        long count = mongoTemplate.count(query,MovementTimeline.class);
        query.skip((publicPageVo.getPage()-1L)*publicPageVo.getPagesize()).limit(publicPageVo.getPagesize().intValue());

        List<MovementTimeline> movementTimelineList = mongoTemplate.find(query, MovementTimeline.class);
        System.out.println(movementTimelineList);
        //处理数据，获得动态id
        List<ObjectId> movementId = CollUtil.getFieldValues(movementTimelineList, "movementId", ObjectId.class);

        //查询对应的动态
        Query movementQuery = new Query(Criteria.where("id").in(movementId)).with(Sort.by(Sort.Order.desc("created")));

        List<Movement> movements = mongoTemplate.find(movementQuery, Movement.class);
        //设置列表
        movementVoResultList.setItems(movements);
        //设置当前页码
        movementVoResultList.setPage(publicPageVo.getPage().intValue());
        //设置总记录数
        movementVoResultList.setCounts((int) count);
        //设置页大小
        movementVoResultList.setPagesize(publicPageVo.getPagesize().intValue());
        //设置总页数
        movementVoResultList.setPages((int) (count%publicPageVo.getPagesize() == 0 ? count/ publicPageVo.getPagesize():(count/ publicPageVo.getPagesize())+1));

        return movementVoResultList;

    }

    @Override
    public ResultList recommendmovements(String[] pidList, PublicPageVo publicPageVo) {
        ResultList<Movement> objectResultList = new ResultList<>();
        //拼凑条件
        Query query = new Query();
        Integer [] newpidList = new Integer[pidList.length];
        for (int i = 0; i < pidList.length; i++) {
            newpidList[i] = Integer.valueOf(pidList[i]);
        }

        query.addCriteria(Criteria.where("pid").in(newpidList)).limit(publicPageVo.getPagesize().intValue()).skip((publicPageVo.getPage()-1)* publicPageVo.getPagesize());
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        System.out.println(movements);
        long count = mongoTemplate.count(query, Movement.class);
        objectResultList.setItems(movements);
        objectResultList.setPagesize(publicPageVo.getPagesize().intValue());
        objectResultList.setPage(publicPageVo.getPage().intValue());
        objectResultList.setPages((int) (count%publicPageVo.getPagesize() == 0 ? count/ publicPageVo.getPagesize():(count/ publicPageVo.getPagesize())+1));
        //返回处理的数据
        return objectResultList;
    }

    @Override
    public Movement findmovement(ObjectId id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        Movement one = mongoTemplate.findOne(query, Movement.class);
        return one;
    }

    @Override
    public List<Movement> randomMovements(Integer count) {
        TypedAggregation<Movement> aggregation = Aggregation.newAggregation(Movement.class, Aggregation.sample(count));
        //进行统计
        AggregationResults<Movement> movementAggregationResults = mongoTemplate.aggregate(aggregation, Movement.class);

        //返回结果
        return movementAggregationResults.getMappedResults();
    }

    @Override
    public Movement likemovement(ObjectId id) {
        //通过动态id查询到该条动态
        Query query = new Query().addCriteria(Criteria.where("id").is(id));
        Movement movement = mongoTemplate.findOne(query, Movement.class);
        //得到点赞数量
        Integer likeCount = movement.getLikeCount();
        //修改数据库点赞数量
        Update update = new Update().set("likeCount", likeCount + 1);
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Movement.class);
        return mongoTemplate.findOne(query,Movement.class);
    }

    @Override
    public Movement dislikemovement(ObjectId id) {
        //通过动态id查询到该条动态
        Query query = new Query().addCriteria(Criteria.where("id").is(id));
        Movement movement = mongoTemplate.findOne(query, Movement.class);
        //得到点赞数量
        Integer likeCount = movement.getLikeCount();
        //修改数据库点赞数量
        Update update = new Update().set("likeCount", likeCount - 1);
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Movement.class);

        return mongoTemplate.findOne(query,Movement.class);
    }

    @Override
    public Movement loveemovement(ObjectId id) {
        //通过动态id查询到该条动态
        Query query = new Query().addCriteria(Criteria.where("id").is(id));
        Movement movement = mongoTemplate.findOne(query, Movement.class);
        //得到点赞数量
        Integer loveCount = movement.getLoveCount();
        //修改数据库点赞数量
        Update update = new Update().set("loveCount", loveCount + 1);
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Movement.class);
        return mongoTemplate.findOne(query,Movement.class);
    }

    @Override
    public Movement unlovemovement(ObjectId id) {
        //通过动态id查询到该条动态
        Query query = new Query().addCriteria(Criteria.where("id").is(id));
        Movement movement = mongoTemplate.findOne(query, Movement.class);
        //得到点赞数量
        Integer loveCount = movement.getLoveCount();
        //修改数据库点赞数量
        Update update = new Update().set("loveCount", loveCount - 1);
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Movement.class);
        return mongoTemplate.findOne(query,Movement.class);
    }
}
